package com.fasttreatment.zzr.demo.db;

import android.content.Context;

import com.fasttreatment.zzr.demo.model.UserRealm;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

import static android.R.attr.id;
import static android.R.attr.name;


/**
 * Created by zzr on 2017/2/4.
 */

public class RealmHelper {

    private static final String DB_NAME = "myRealm.realm";
    private Realm mRealm;

    public RealmHelper(Context mContext) {
        mRealm = Realm.getInstance(new RealmConfiguration.Builder(mContext)
                .deleteRealmIfMigrationNeeded()
                .name(DB_NAME)
                .build());
    }


    /**
     * 新增用户
     * 使用@PrimaryKey注解后copyToRealm需要替换为copyToRealmOrUpdate
     *
     * @param userRealm
     */
    public boolean insertUser(UserRealm userRealm) {
        mRealm.beginTransaction();
        mRealm.copyToRealmOrUpdate(userRealm);
        mRealm.commitTransaction();
        return false;
    }



    /**
     * 查询用户
     *
     * @param userRealm
     * @return
     */
    public boolean queryUser(UserRealm userRealm) {
        RealmResults<UserRealm> realmResults = mRealm.where(UserRealm.class).findAll();
        for (UserRealm realmResult : realmResults) {
            if (realmResult.getUsername().equals(userRealm.getUsername()) && realmResult.getPassword().equals(userRealm.getPassword())) {
                return true;
            }

        }
        return false;
    }
    public void close(){
        if (mRealm!=null){
            mRealm.close();
        }
    }
}
